<?php
function logged_in(){
	if(isset($_SESSION["ACCOUNT"])){
		return true;
	}
	return false;
}

function login($username, $password){
	$username = mysql_real_escape_string($username);
	$password = md5($password);
	$query = "SELECT account_id, userid FROM login WHERE userid = '".$username."' AND user_pass = '".$password."';";
	$result = mysql_query($query) or die(mysql_error());
	$size = mysql_num_rows($result);
	if($size==1){
		// session key fixen
		$record = mysql_fetch_assoc($result);
		$_SESSION["ACCOUNT"] = $record["account_id"];
		$_SESSION["USERNAME"] = $record["userid"];
		$_SESSION["IP"] = $_SERVER["REMOTE_ADDR"];
		return true;
	}
	return false;
}

function siteApproved($url, $votingSites){
	$approvedSite = false;
	foreach ($votingSites as $site){
		if($site["url"] == $url){
			return true;
		}
	}
	return false;
}

function canVoteForSite($url, $votingSites){
	if(siteApproved($url, $votingSites)){
		$votingdelay = 24;
		foreach ($votingSites as $site){
			if($site["url"] == $url){
				$votingdelay = $site["time"];
			}
		}
		$ip = $_SESSION["IP"];
		$acc = $_SESSION["ACCOUNT"];
		$query = "SELECT count(*) AS result FROM `voting_history` WHERE UNIX_TIMESTAMP(last_vote) > (UNIX_TIMESTAMP() - (3600 * $votingdelay)) AND voting_site = '$url' AND (vote_ip = '$ip' OR account_id = '$acc');";
		$result = mysql_query($query) or die(mysql_error());
		$record = mysql_fetch_assoc($result);
		if($record["result"] == 0){
			return true;
		}
	}
	return false;
}

function voteForSite($url, $votingSites){
	// check if site exists in our list - if not it's no vote, so no credit!
	if(!siteApproved($url, $votingSites)){
		return false;
	}
	// add to voting history
	$url = mysql_real_escape_string($url);
	$ip = $_SESSION["IP"]; 
	$acc_id = $_SESSION["ACCOUNT"];
	$query = "INSERT INTO voting_history (vote_ip, account_id, voting_site) VALUES ('$ip', '$acc_id', '$url') ON DUPLICATE KEY UPDATE last_vote = CURRENT_TIMESTAMP";
	$result = mysql_query($query) or die(mysql_error());
	// add a credit
	$query = "INSERT INTO cp_credits (account_id, balance) VALUES ('$acc_id', '1') ON DUPLICATE KEY UPDATE balance = balance + 1";
	$result = mysql_query($query) or die(mysql_error());
	return true;
}
?>